package dcp.bss.modules.bussiness.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Wrapper;
import dcp.bss.common.model.CmdLockBean;
import dcp.bss.common.model.KeyValueBean;
import dcp.bss.common.util.DBUtil;
import dcp.bss.common.util.R;
import dcp.bss.modules.bussiness.entity.DeviceEntity;
import dcp.bss.modules.bussiness.entity.DeviceOprLogEntity;
import dcp.bss.modules.bussiness.service.DeviceOprLogService;
import dcp.bss.modules.bussiness.service.DeviceService;
import dcp.bss.modules.sys.entity.SysUserEntity;
import dcp.bss.web.exception.RRException;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.List;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import dcp.bss.common.util.PageUtils;
import dcp.bss.web.util.Query;
import dcp.bss.query.QueryViewVo;
import dcp.bss.modules.bussiness.dao.LockStatusDao;
import dcp.bss.modules.bussiness.entity.LockStatusEntity;
import dcp.bss.modules.bussiness.service.LockStatusService;
import org.springframework.transaction.annotation.Transactional;


@Service("baseMapper")
public class LockStatusServiceImpl extends ServiceImpl<LockStatusDao, LockStatusEntity> implements LockStatusService {
    @Autowired
    private DeviceOprLogService deviceOprLogService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private LockStatusService lockStatusService;
    @Autowired
    private StringRedisTemplate template;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<LockStatusEntity> page = this.selectPage(
                new Query<LockStatusEntity>(params).getPage(),
                new EntityWrapper<LockStatusEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(QueryViewVo<LockStatusEntity> queryViewVo) {
        Wrapper<LockStatusEntity> ew = queryViewVo.getWrapper();
        SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();

        if (sysUserEntity.getIpPk() == 0) {
        } else {
            ew.eq("carrier_name",sysUserEntity.getIpName());
        }
        Page<LockStatusEntity> page = this.selectPage(queryViewVo.getPageUtil(),
                ew);
        return new PageUtils(page);
    }

    @Override
    public List<LockStatusEntity> download(QueryViewVo<LockStatusEntity> queryViewVo) {
        List<LockStatusEntity> list = this.selectList(queryViewVo.getWrapper());
        return list;
    }

    @Override
    public LockStatusEntity selectByCode(String lockNum) {
        LockStatusEntity lockStatusEntity = this.selectOne(new EntityWrapper<LockStatusEntity>().eq("lock_code", lockNum));
        return lockStatusEntity;
    }

    @Override
    @Transactional
    public R unlock(String lockNum, Double lng, Double lat) {
        SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        DeviceEntity deviceEntity = deviceService.selectByCode(lockNum);
        CmdLockBean cmdLockBean = new CmdLockBean();
        //32是施封 38 是解封
        cmdLockBean.setCmd(38);
        cmdLockBean.setLockDevID(Integer.parseInt(lockNum));
        cmdLockBean.setLockType(Integer.parseInt(deviceEntity.getCatCd()));
        cmdLockBean.setPassword(deviceEntity.getPassword());
        template.convertAndSend("oprLock", JSONObject.toJSONString(cmdLockBean));
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        DeviceOprLogEntity deviceOprLog = new DeviceOprLogEntity();
        deviceOprLog.setDeviceCode(lockNum);
        deviceOprLog.setOprTm(new Date());
        deviceOprLog.setOprType("解封");
        deviceOprLog.setOprator(sysUserEntity.getIpName());
        if (lng != null && lat != null) {
            deviceOprLog.setLng(lng);
            deviceOprLog.setLat(lat);
        }
        try {
            for (int i = 0; i < 5; i++) {
                String sql = "SELECT lock_status,cmd_src FROM `biz_lock_status` where lock_code=" + lockNum;

                List<KeyValueBean> result = DBUtil.executeQuery(sql);
                if (result != null && result.size() > 0) {
                    String lockStatus = (String) result.get(0).getKey();
                    String cmdSrc = (String) result.get(0).getValue();
                    if (lockStatus.contains("解封") || lockStatus.contains("开启")) {
                        deviceOprLog.setCmdSrc(cmdSrc);
                        deviceOprLog.setLockStatus(lockStatus);
                        deviceOprLog.setResult("解封成功");
                        deviceOprLogService.insert(deviceOprLog);
                        return R.ok("解封成功");
                    } else {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        deviceOprLog.setResult("解封失败");
        deviceOprLogService.insert(deviceOprLog);
        return R.error("解封失败");


    }

    @Override
    @Transactional
    public R lock(String lockNum, Double lng, Double lat) {
        SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        DeviceEntity deviceEntity = deviceService.selectByCode(lockNum);
        CmdLockBean cmdLockBean = new CmdLockBean();
        //32是施封 38 是解封
        cmdLockBean.setCmd(32);
        cmdLockBean.setLockDevID(Integer.parseInt(lockNum));
        cmdLockBean.setLockType(Integer.parseInt(deviceEntity.getCatCd()));
        cmdLockBean.setPassword(deviceEntity.getPassword());
        template.convertAndSend("oprLock", JSONObject.toJSONString(cmdLockBean));
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        DeviceOprLogEntity deviceOprLog = new DeviceOprLogEntity();
        deviceOprLog.setDeviceCode(lockNum);
        deviceOprLog.setOprTm(new Date());
        deviceOprLog.setOprType("施封");
        deviceOprLog.setOprator(sysUserEntity.getIpName());
        if (lng != null && lat != null) {
            deviceOprLog.setLng(lng);
            deviceOprLog.setLat(lat);
        }
        try {
            for (int i = 0; i < 5; i++) {
                String sql = "SELECT lock_status,cmd_src FROM `biz_lock_status` where lock_code=" + lockNum;

                List<KeyValueBean> result = DBUtil.executeQuery(sql);
                if (result != null && result.size() > 0) {
                    String lockStatus = (String) result.get(0).getKey();
                    String cmdSrc = (String) result.get(0).getValue();
                    if (lockStatus.contains("施封") || lockStatus.contains("锁定")) {
                        deviceOprLog.setCmdSrc(cmdSrc);
                        deviceOprLog.setLockStatus(lockStatus);
                        deviceOprLog.setResult("施封成功");
                        deviceOprLogService.insert(deviceOprLog);
                        return R.ok("施封成功");
                    } else {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        deviceOprLog.setResult("施封失败");
        deviceOprLogService.insert(deviceOprLog);
        return R.error("施封失败");
    }

}
